﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.LocalDatabase;
using ComicIsland.Common.Entities.LocalJson;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.CacheManage
{
    public partial class ComicPage : PhoneApplicationPage
    {
        private bool IsNeedReloadData = false;
        private ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.None;


        public ComicPage()
        {
            InitializeComponent();

            this.IsNeedReloadData = true;
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.IsNeedReloadData = false;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //加载下载过的漫画列表
            if (this.IsNeedReloadData)
            {
                LoadLDBComics();
            }

            base.OnNavigatedTo(e);
        }

        /// <summary>
        /// 加载缓存的漫画列表
        /// </summary>
        void LoadLDBComics()
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                this.lst.ItemsSource = App.dbContextHelper.GetAllComics();
            });
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            //找到当前CheckBox的所在ListBoxItem
            ListBoxItem lbi = Helper.FindParentOfType<ListBoxItem>(chk);
            if (lbi != null)
                lbi.IsSelected = true;
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {

        }

        private void lst_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void gridComic_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LDBComic item = (sender as Grid).DataContext as LDBComic;
            if (item == null)
                return;
            string param = string.Concat("?comicId=", item.ComicId, "&bookId=", item.BookId);
            NaviService.Navigate(ComicIslandPage.DCVDownloadQueuePage, param);
        }



        private void appBarCheck_Click(object sender, EventArgs e)
        {
            var appBarIcon = sender as ApplicationBarIconButton;
            if (appBarIcon == null)
                return;

            this.Dispatcher.BeginInvoke(() =>
            {
                if ("选择全部".Equals(appBarIcon.Text))
                {
                    appBarIcon.Text = "取消全选";
                    appBarIcon.IconUri = new Uri("/Images/Icons/uncheckedall.png", UriKind.Relative);
                    this.lst.SelectAll();
                    selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.All;
                }
                else
                {
                    appBarIcon.Text = "选择全部";
                    appBarIcon.IconUri = new Uri("/Images/Icons/checkedall.png", UriKind.Relative);
                    this.lst.SelectedItems.Clear();
                    selectedStatus = ComicIsland.App.Views.CacheManage.CacheManageCommon.SelectedStatus.UnAll;
                }
            });
        }

        private void appBarDelete_Click(object sender, EventArgs e)
        {
            if (this.lst.SelectedItems.Count <= 0)
            {
                MessageToastManager.Show("请选择要删除的漫画！");
                return;
            }

            if (MessageBoxResult.OK != MessageBox.Show(string.Format("确认删除选中的 {0} 个缓存漫画？", this.lst.SelectedItems.Count), AppResources.ApplicationTitle, MessageBoxButton.OKCancel))
            {
                return;
            }

            var sources = this.lst.ItemsSource as ObservableCollection<LDBComic>;
            if (!(sources != null && sources.Count > 0))
                return;

            while (this.lst.SelectedItems.Count > 0)
            {
                var item = this.lst.SelectedItems[0] as LDBComic;
                if (item == null)
                    continue;

                try
                {
                    //删除漫画、漫画中的章节、漫画中章节的图片
                    App.dbContextHelper.RemoveComicChapterImageByComicId(item.ComicId, item.BookId);
                    App.dbContextHelper.RemoveComicChapterByComicId(item.ComicId, item.BookId);
                    App.dbContextHelper.RemoveComicByComicId(item.ComicId, item.BookId);
                    //TODO 删除数据库信息后，已下载的缓存信息也需要删除
                    //删除数据库信息后，书架也需要删除
                    LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
                    if (item.ComicId > 0 || item.BookId > 0)
                    {
                        var bookcaseInfo = helper.Get(item.ComicId);
                        if (bookcaseInfo != null)
                        {
                            bookcaseInfo.IsSync = false;
                            bookcaseInfo.Status = LocalBookcaseStatus.Delete.ToString();
                            bookcaseInfo.LocalUpdateDate = DateTime.Now.ToString(KEYS.DATE_FORMAT_YMD);
                            if (new LocalBookcaseInfoHelper().Update(bookcaseInfo))
                            {
                                //TODO 同步至服务器                        
                                new WinPhoneDataUpdateHelper().SyncBookcaseInfo(KEYS.WpDataUpdateType.bookHandle, KEYS.WpDataUpdateTypeSyncBook.Deleted, bookcaseInfo);
                            }
                        }
                    }
                    //
                    sources.Remove(item);
                }
                catch (Exception err)
                {
                    LogHelper.LogInfo(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                }
            }
        }
    }
}